import win32com.client 
from datetime import date,timedelta

from ReportTool.HldReport import *
from Reports.CPPIB_MTD_Report import *

from Config.ReportConfig import *

def ActiveWeight(ref_date):

	portf_id = 'SC032'
	idx_ticker = '816000'
	
	d = date(2013, 7, 10)
	
	rcd = []
	while d <= ref_date:
	
		idx = query_index_weight(d, idx_ticker)
		
		if idx:
			oneday_rcd = {}
			hld = query_hld(d, [portf_id])
			
			for elem in idx:
				oneday_rcd[(d, elem[0])] = [elem[4], None]
		
			for elem in hld:
				if elem[2] == 'CASH' or elem[2] == 'REPO':
					continue
				if oneday_rcd.has_key((d, elem[0])):
					oneday_rcd[(d, elem[0])][1] = elem[12]
				else:
					oneday_rcd[(d, elem[0])] = [None, elem[12]]
					
			rcd.append(oneday_rcd)
			
		d += timedelta(days = 1)
	
	#Write
	tplt_file = TPLT_PATH + 'Active Weight.xls'
	xApp = win32com.client.Dispatch("Excel.Application")
	xBook = xApp.Workbooks.Open(tplt_file)
	xSht = xBook.Worksheets('ActiveWeight')
	
	row = 2
	for elem in rcd:
		for k, v in elem.iteritems():
			xSht.Cells(row, 1).Value = k[0]
			xSht.Cells(row, 2).Value = k[1]
			xSht.Cells(row, 3).Value = v[0]
			xSht.Cells(row, 4).Value = v[1]
			row += 1
	
	rept_file = REPT_PATH + 'Active Weight_' + ref_date.strftime("%Y%m%d") + '.xls'
	xBook.SaveAs(rept_file)
	xBook.Close()
	del xApp
	
	print 'info, CPPIB active weight report completed at ', ref_date.isoformat()
	